package com.ttloner.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author TTLoner
 * @date 2021/7/5 18:20
 * @description
 */
public class JDBCUtils {

    private static DataSource dataSource;
    //静态代码块实现创建线程池
    static{
        Properties properties= new Properties();
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(inputStream);
            dataSource = (DataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * @author: TTLoner
     * @time: 2021/7/5 18:21
     * @description:
     *  获取数据库连接池中的连接
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //
        return conn;
    }
    /*
     * @author: TTLoner
     * @time: 2021/7/5 18:23
     * @description:
     *  重置线程状态，放回数据库连接池
     */

    public static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
